package com.baosight.risk.web.netty;

import com.baosight.risk.common.result.AjaxResult;
import com.baosight.risk.common.utils.ReadProperties;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Slf4j
//@Component("socketIO")
@org.springframework.context.annotation.Configuration
public class SocketIO {
    static SocketIOServer server;
    static List<SocketIOClient> clientQueue = new LinkedList<>();

    //@PostConstruct
    public void startSocket() {
        new Thread(() -> {
            socketStart();
        }).start();
    }

    private void socketStart() {
        log.info("in socketio");
        // TODO Auto-generated method stub
        Configuration config = new Configuration();
        config.setHostname(ReadProperties.getValueString("nettySocketPath"));
        config.setPort(Integer.valueOf(ReadProperties.getValueString("nettySocketport")));
        config.setMaxFramePayloadLength(1024 * 1024);
        config.setMaxHttpContentLength(1024 * 1024);
        server = new SocketIOServer(config);

        server.addEventListener("sendEvent", AjaxResult.class, (client, data, ackRequest) -> {
            // send message back to client with ack callback WITH data
//            ChatObject ackChatObjectData = new ChatObject("system", "admin", "本地服务有哥待办8090");
            Map<String, String> msg = new HashMap<>();
            msg.put("sender", "system");
            msg.put("receiver", "admin");
            msg.put("dept", "BGTA");
            msg.put("type", "task");
            msg.put("content", "您有一条新的待办任务！");

            AjaxResult result = AjaxResult.success();
            result.put("data", msg);

            server.getBroadcastOperations().sendEvent("notifyInfo", result);
        });

        //添加客户端连接事件
        server.addConnectListener(new ConnectListener() {
            @Override
            public void onConnect(SocketIOClient client) {
                // TODO Auto-generated method stub
                String sa = client.getRemoteAddress().toString();
                String clientIp = sa.substring(1, sa.indexOf(":"));//获取设备ip
                System.out.println(clientIp + "-------------------------" + "客户端已连接");
                Map params = client.getHandshakeData().getUrlParams();

//                //获取客户端连接的uuid参数
//                Object object = params.get("uuid");
//                String uuid = "";
//                if (object != null) {
//                    uuid = ((List<String>) object).get(0);
//                    //将uuid和连接客户端对象进行绑定
//                    clientsMap.put(uuid, client);
//                }
//                //给客户端发送消息
//                client.sendEvent("advert_info", clientIp + "客户端你好，我是服务端，有什么能帮助你的？");
            }
        });

        server.start();
        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            log.error(e.getMessage());
            Thread.currentThread().interrupt();
        }
        server.stop();
    }

    /**
     * 给所有连接客户端推送消息，给多个人发待办
     */
    public void sendTaskMsgToAll(List<XtzyUser> users) {
        if (CollectionUtils.isNotEmpty(users)) {
            for (XtzyUser user : users) {
                Map<String, String> msg = new HashMap<>();
                msg.put("sender", "system");
                msg.put("status", user.getExt3());
                msg.put("receiver", user.getUserCode());
                msg.put("dept", user.getExt1());
                msg.put("type", "task");
                msg.put("content", "您有一条新的待办任务！");

                AjaxResult result = AjaxResult.success();
                result.put("data", msg);
                server.getBroadcastOperations().sendEvent("notifyInfo", result);

            }
        }
    }

    /**
     * 给所有连接客户端推送消息，指定用户发送待办
     */
    public void sendTaskMsgToAll(XtzyUser user) {
        if (user != null) {
            Map<String, String> msg = new HashMap<>();
            msg.put("sender", "system");
            msg.put("status", user.getExt3());
            msg.put("receiver", user.getUserCode());
            msg.put("dept", user.getExt1());
            msg.put("type", "task");
            msg.put("content", "您有一条新的待办任务！");

            AjaxResult result = AjaxResult.success();
            result.put("data", msg);
            server.getBroadcastOperations().sendEvent("notifyInfo", result);

        }
    }

    /**
     * 给所有连接客户端推送消息，给多个人发待办
     */
    public void sendMsgToAll(List<XtzyUser> users) {
        if (CollectionUtils.isNotEmpty(users)) {
            for (XtzyUser user : users) {
                Map<String, String> msg = new HashMap<>();
                msg.put("sender", "system");
                msg.put("status", user.getExt3());
                msg.put("receiver", user.getUserCode());
                msg.put("dept", user.getExt1());
                msg.put("type", "msg");
                msg.put("content", "您有一条新的未读消息！");

                AjaxResult result = AjaxResult.success();
                result.put("data", msg);
                server.getBroadcastOperations().sendEvent("notifyInfo", result);

            }
        }
    }

    /**
     * 给所有连接客户端推送消息，指定用户发送消息通知
     */
    public void sendMsgToAll(XtzyUser user) {
        if (user != null) {
            Map<String, String> msg = new HashMap<>();
            msg.put("sender", "system");
            msg.put("status", user.getExt3());
            msg.put("receiver", user.getUserCode());
            msg.put("dept", user.getExt1());
            msg.put("type", "msg");
            msg.put("content", "您有一条新的未读消息！");

            AjaxResult result = AjaxResult.success();
            result.put("data", msg);
            server.getBroadcastOperations().sendEvent("notifyInfo", result);
        }
    }

}
